﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace Shopping.Common
{
    public class ImageHelper
    {
        #region "更改指定图片的尺寸。"
        /// <summary>
        /// 更改指定图片的尺寸。
        /// </summary>
        /// <remarks>
        /// 如果原图片的宽度大于长度，新图片以newMaxWidth为最大边进行缩放。<br></br>
        /// 如果原图片的长度大于宽度，新图片以newMaxHeignt为最大边进行缩放。
        /// </remarks>
        /// <param name="oldImageFile">原图片全路径</param>
        /// <param name="newImageFile">新图片全路径，如果已经有同名文件存在，将被覆盖</param>
        /// <param name="newMaxWidth">新图片的最大宽度，以像素为单位</param>
        /// <param name="newMaxHeight">新图片的最大长度，以像素为单位</param>
        /// <returns></returns>
        public static ReturnValue ResizeImage(string oldImageFile, string newImageFile, int newMaxWidth, int newMaxHeight)
        {
            ReturnValue ret = new ReturnValue(ResultType.Fail);
            if (newMaxWidth <= 0 || newMaxHeight <= 0)
            {
                ret.Message = "新图片的宽度和高度必须大于0!";
                return ret;
            }

            try
            {
                Bitmap myBitmap = new Bitmap(oldImageFile);
                int imageWidth, imageHeight;
                if (myBitmap.PhysicalDimension.Width / newMaxWidth - myBitmap.PhysicalDimension.Height / newMaxHeight > 0)
                {
                    //以宽度为主；
                    imageWidth = newMaxWidth;
                    imageHeight = (int)((newMaxWidth / myBitmap.PhysicalDimension.Width) * myBitmap.PhysicalDimension.Height);
                }
                else
                {
                    //以高度为主；
                    imageHeight = newMaxHeight;
                    imageWidth = (int)((newMaxHeight / myBitmap.PhysicalDimension.Height) * myBitmap.PhysicalDimension.Width);
                }
                ret = Resize(oldImageFile, newImageFile, newMaxWidth, newMaxHeight, imageWidth, imageHeight);
                myBitmap.Dispose();
                return ret;
            }
            catch (Exception e)
            {
                ret.Message = e.Message;
            }
            return ret;
        }




        /// <summary>
        /// 更改指定图片的尺寸。
        /// </summary>		
        /// <param name="oldImageFile">原图片全路径</param>
        /// <param name="newImageFile">新图片全路径，如果已经有同名文件存在，将被覆盖</param>
        /// <param name="newSizePercent">新图片的尺寸与原图片尺寸的百分比，超过100%为放大图片，在0与100%之间为缩小图片</param>
        /// <returns></returns>
        public static ReturnValue ResizeImage(string oldImageFile, string newImageFile, int newSizePercent)
        {
            ReturnValue ret = new ReturnValue(ResultType.Fail);
            if (newSizePercent <= 0)
            {
                ret.Message = "新图片尺寸百分比必须大于0!";
                return ret;
            }

            try
            {
                Bitmap myBitmap = new Bitmap(oldImageFile);
                float imageWidth = myBitmap.PhysicalDimension.Width / 100 * newSizePercent;
                float imageHeight = myBitmap.PhysicalDimension.Height / 100 * newSizePercent;
                ret = Resize(oldImageFile, newImageFile, (int)imageWidth, (int)imageHeight, (int)imageWidth, (int)imageHeight);
                myBitmap.Dispose();
                return ret;
            }
            catch (Exception e)
            {
                ret.Message = e.Message;
            }
            return ret;
        }

        #endregion

        #region "内部执行具体的图片缩放操作"

        /// <summary>
        /// 执行具体的图片缩放操作
        /// </summary>
        /// <param name="oldImageFile"></param>
        /// <param name="newImageFile"></param>
        /// <param name="newWidth"></param>
        /// <param name="newHeight"></param>
        /// <returns></returns>
        private static ReturnValue Resize(string oldImageFile, string newImageFile, int newMaxWidth, int newMaxHeight, int newWidth, int newHeight)
        {
            ReturnValue ret = new ReturnValue(ResultType.Fail);
            try
            {

                //调用Discuz的类来执行操作                
                MakeThumbnail(oldImageFile, newImageFile, newMaxWidth, newMaxHeight, newWidth, newHeight);

                ret.Result = ResultType.Success;
            }
            catch (Exception e)
            {
                ret.Message = e.Message;
            }
            return ret;
        }





        /**/
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>        
        private static void MakeThumbnail(string originalImagePath, string thumbnailPath, int newWidth, int newHeight, int width, int height)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            //switch (mode)
            //{
            //    case "HW"://指定高宽缩放（可能变形）                
            //        break;
            //    case "W"://指定宽，高按比例                    
            //        toheight = originalImage.Height * width / originalImage.Width;
            //        break;
            //    case "H"://指定高，宽按比例
            //        towidth = originalImage.Width * height / originalImage.Height;
            //        break;
            //    case "Cut"://指定高宽裁减（不变形）                
            //        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
            //        {
            //            oh = originalImage.Height;
            //            ow = originalImage.Height * towidth / toheight;
            //            y = 0;
            //            x = (originalImage.Width - ow) / 2;
            //        }
            //        else
            //        {
            //            ow = originalImage.Width;
            //            oh = originalImage.Width * height / towidth;
            //            x = 0;
            //            y = (originalImage.Height - oh) / 2;
            //        }
            //        break;
            //    default:
            //        break;
            //}

            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(newWidth, newHeight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle((newWidth - towidth) / 2, (newHeight - toheight) / 2, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 图片处理程序的回调函数，没有实际意义
        /// </summary>
        /// <returns></returns>
        public static bool ThumbnailCallback()
        {
            return false;
        }
        #endregion
    }
}
